package com.yami.shop.platform.controller;

import com.yami.shop.common.kdniao.KdNiaoNotify;
import com.yami.shop.common.kdniao.KdniaoConfig;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@Slf4j
@RestController
@RequestMapping("/kd/notify")
public class KdniaoNotifyController {

    @Autowired
    private KdNiaoNotify kdNiaoNotify;

    @ApiOperation(value = "快递鸟异步通知", notes = "快递鸟异步通知")
    @PostMapping("/message")
    public void message(HttpServletRequest request, HttpServletResponse response){
        log.info("快递鸟异步通知=============start");
        StringBuilder sb = new StringBuilder();
        ServletInputStream inputStram = null;
        try {
            inputStram = request.getInputStream();
            log.info("快递鸟异步通知====开始执行while循环 start");
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStram, "utf-8"));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                log.info("快递鸟异步通知===start===" + temp);
                sb.append(temp);
                log.info("快递鸟异步通知===end===" + temp);
            }
            log.info("快递鸟异步通知====开始执行while循环 end");
            br.close();
            log.info("快递鸟异步通知 post content is " + sb.toString());
        }catch (Exception e) {
            e.printStackTrace();
            log.info("快递鸟异步通知=============异常1{}",e.getMessage());
        }
        log.info("快递鸟异步通知 request_xml = " + sb.toString());
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("charset=UTF-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.append(kdNiaoNotify.responseStr(KdniaoConfig.EBusinessID));
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
            log.info("快递鸟异步通知=============异常2{}",e.getMessage());
        }finally{
            log.info("快递鸟异步通知=============end");
        }
    }

}
